package com.jinlejia.erp.ui.mine.sign;

import android.Manifest;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivitySignInBinding;
import com.jinlejia.erp.ui.common.PermissionDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jinlejia.erp.utils.SharePTool;
import com.jinlejia.erp.utils.StringUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import cn.aigestudio.datepicker.bizs.calendars.DPCManager;
import cn.aigestudio.datepicker.bizs.decors.DPDecor;
import cn.aigestudio.datepicker.cons.DPMode;
import cn.aigestudio.datepicker.views.DatePicker;
import cn.aigestudio.datepicker.views.MonthView;
import okhttp3.Call;
import okhttp3.MediaType;

import static com.zhy.http.okhttp.OkHttpUtils.postString;

/**
 * 签到（activity）
 */

public class SignInActivity extends AppCompatActivity implements OnDateSetListener {
    private JSONObject jsonObject = new JSONObject();
    private String year1;
    private String month1;
    private List<String> tmpTL;
    private List<String> tmpTR;
    private ProgressDialog progressDialog;
    private ProgressDialog LocationDialog;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private double distance = 10000, locationRadius = 0;
    private ArrayList<Map<String, String>> storeList = new ArrayList<>();
    private PermissionDialog permissionDialog;
    private String currentLocation;
    private double lat, lng;
    private DialogSignState dialogSignState;

    private ActivitySignInBinding binding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_sign_in);
        binding.setEvent(this);
        EventBus.getDefault().registerSticky(this);
        initView();
    }

    /**
     * 初始化视图
     */
    private void initView() {
        progressDialog = new ProgressDialog(this, "请稍等...");
        LocationDialog = new ProgressDialog(this, "正在定位中...");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy");
        year1 = sdf1.format(new java.util.Date());
        SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
        month1 = sdf2.format(new java.util.Date());
        binding.mainDp.setDate(Integer.parseInt(year1), Integer.parseInt(month1));
        binding.mainDp.setFestivalDisplay(false);
        binding.mainDp.setTodayDisplay(false);
        binding.mainDp.setHolidayDisplay(false);
        binding.mainDp.setDeferredDisplay(false);
        binding.mainDp.setMode(DPMode.SINGLE);
        binding.mainDp.setImage(getResources().getDrawable(R.mipmap.calendar_icon));
        binding.mainDp.setOnTitleClickListener(() -> {
            TimePickerDialog calendarPicker = new TimePickerDialog.Builder()
                    .setType(Type.YEAR_MONTH)
                    .setTitleStringId("选择时间")
                    .setCurrentMillseconds(System.currentTimeMillis())
                    .setThemeColor(getResources().getColor(R.color.yellow))
                    .setWheelItemTextNormalColor(getResources().getColor(R.color.hintColor))
                    .setWheelItemTextSelectorColor(getResources().getColor(R.color.yellow))
                    .setCallBack(SignInActivity.this)
                    .build();
            calendarPicker.show(getSupportFragmentManager(), "year_month");
        });
        binding.mainDp.setOnDatePickedListener(date -> {
            if (DateUtil.date2TimeStamp(date, "yyyy-M-d") < System.currentTimeMillis()) {
                dialogSignState = new DialogSignState(SignInActivity.this);
                dialogSignState.show();
                queryDayDetail(date);
            }
        });

        if (getIntent().hasExtra("MainStartSign")) {
            //推送跳转
            getInfoData();
        } else {
            QuerySign();
        }

        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        option.disableCache(true);
        option.setScanSpan(20 * 1000); // 多长时间进行一次请求
        option.setPriority(LocationClientOption.GpsFirst); //设置GPS优先
        option.setIsNeedLocationDescribe(true);
//        option.setIsNeedLocationPoiList(true);
        mLocClient.setLocOption(option);

        if (null == permissionDialog)
            permissionDialog = new PermissionDialog(this);
        XXPermissions.with(this)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        System.out.println(granted.toString());
                        mLocClient.start();
                        LocationDialog.show();
                        if (isAll && permissionDialog.isShowing()) {
                            permissionDialog.dismiss();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (null != permissionDialog && !permissionDialog.isShowing())
                            permissionDialog.show();
                        permissionDialog.setConfirmListener(() -> XXPermissions.gotoPermissionSettings(SignInActivity.this));
                    }
                });


        binding.mainDp.setOnTimeChangeListener(new MonthView.OnDateChangeListener() {
            @Override
            public void onMonthChange(int month) {
            }

            @Override
            public void onYearChange(int year) {
            }

            @Override
            public void onYearMonthChange(int year, int month) {
                month1 = String.valueOf(month);
                year1 = String.valueOf(year);
                QuerySign();
            }
        });

    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.sign_manager:
                //管理
                startActivity(new Intent(SignInActivity.this, SignManagerActivity.class));
                break;
            case R.id.sign_in:
                if (distance <= locationRadius) {
                    AddSign(1);
                } else {
                    CustomToast.showToast(SignInActivity.this, "您还没有到公司呦～", 1500);
                }
                break;
            case R.id.sign_out:
                //签退
                if (distance <= locationRadius) {
                    AddSign(2);
                } else {
                    CustomToast.showToast(SignInActivity.this, "您没在公司呦～", 1500);
                }
                break;
            case R.id.field_sign_in:
                //外勤打卡
                if (null != binding.signIn.getTag() && binding.signIn.getTag().equals(1) && null != binding.signOut.getTag() && binding.signOut.getTag().equals(1)) {
                    //已经签到、签退
                    CustomToast.showToast(SignInActivity.this, "今日已完成签到", 1500);
                } else if (TextUtils.isEmpty(currentLocation)) {
                    CustomToast.showToast(SignInActivity.this, "定位当前位置失败", 1500);
                } else {
                    Intent intent = new Intent(SignInActivity.this, FieldSignInActivity.class);
                    intent.putExtra("cur_location", currentLocation);
                    intent.putExtra("lat", lat);
                    intent.putExtra("lng", lng);
                    startActivityForResult(intent, 101);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 101) {
                //外勤签到成功
                QuerySign();
            }
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millseconds);
        binding.mainDp.setDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
    }

    /**
     * 签到
     */
    public void AddSign(int type) {
        progressDialog.show();
        OkHttpUtils
                .postString()
                .url(ApiConfig.ADD_SIGN_IN + type)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content("")
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(SignInActivity.this, response)) {
                            if (null != tmpTL && tmpTL.size() > 0)
                                tmpTL.clear();
                            if (null != tmpTR && tmpTR.size() > 0)
                                tmpTR.clear();
                            QuerySign();
                        }
                    }
                });

    }

    /**
     * 查询签到
     */
    public void QuerySign() {
        jsonObject.put("year", year1);
        jsonObject.put("month", month1);
        postString()
                .url(ApiConfig.QUERY_SIGN_IN)
                .content(jsonObject.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(SignInActivity.this, response)) {
                            //迟到日期集合
                            tmpTL = new ArrayList<>();
                            //签到日期集合
                            tmpTR = new ArrayList<>();
                            ArrayList<String> dateList = new ArrayList<>();
                            JSONObject object = JSON.parseObject(response.get("data").toString());
                            locationRadius = object.getDouble("locationRadius");
                            ArrayList<Map<String, Object>> list = JSON.parseObject(object.get("page").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            //今天日期
                            final String todayDateLine = getNowTime();
                            for (int i = 0; i < list.size(); i++) {
                                //循环de当前日期
                                String dateline = DateUtil.getTime(list.get(i).get("signTime").toString(), "yyyy-M-d");
                                if (!dateList.contains(dateline))
                                    dateList.add(dateline);
                                if (list.get(i).get("signState").toString().equals("1")) { //已签到/签退
                                    if (!tmpTL.contains(dateline))
                                        tmpTR.add(dateline);

                                } else if (list.get(i).get("signState").toString().equals("2") ||
                                        list.get(i).get("signState").toString().equals("3")) { //迟到/早退
                                    if (tmpTR.contains(dateline)) {
                                        //有迟到早退情况，从正常list中清除
                                        tmpTR.remove(dateline);
                                    }
                                    tmpTL.add(dateline);

                                }
                                if (dateline.equals(todayDateLine)) {
                                    //今日
                                    if (list.get(i).get("type").toString().equals("1")) {
                                        //已上班签到
                                        binding.signIn.setBackgroundResource(R.drawable.shape_info_btn_grey);
                                        binding.signIn.setClickable(false);
                                        binding.signIn.setFocusable(false);
                                        binding.signIn.setText("上班签到成功");
                                        //标记已经签到
                                        binding.signIn.setTag(1);
                                    } else if (list.get(i).get("type").toString().equals("2")) {
                                        //已下班签退
                                        binding.signOut.setBackgroundResource(R.drawable.shap_border_grey);
                                        binding.signOut.setTextColor(Color.parseColor("#CCCCCC"));
                                        binding.signOut.setClickable(false);
                                        binding.signOut.setFocusable(false);
                                        binding.signOut.setText("下班签退成功");
                                        //标记已经签退
                                        binding.signOut.setTag(1);
                                    }
                                } else {
                                    dateList.add(todayDateLine);
                                }

                            }
                            if (dateList.size() > 0) {
                                DPCManager.getInstance().clearnDATE_CACHE();
                                binding.mainDp.monthView.postInvalidate();
                                DPCManager.getInstance().setDecorBG(dateList);
                                binding.mainDp.setDPDecor(new DPDecor() {
                                    @Override
                                    public void drawDecorBG(Canvas canvas, Rect rect, Paint paint, String data) {
                                        super.drawDecorBG(canvas, rect, paint, data);
                                        if (tmpTR.contains(data)) {
                                            paint.setColor(getResources().getColor(R.color.yellow));
                                            canvas.drawCircle(rect.centerX(), rect.centerY(), rect.width() / 2.5F, paint);
                                        }
                                        if (tmpTL.contains(data)) {
                                            paint.setColor(getResources().getColor(R.color.orange));
                                            canvas.drawCircle(rect.centerX(), rect.centerY(), rect.width() / 2.5F, paint);
                                        }
                                        if (!tmpTL.contains(todayDateLine) && !tmpTR.contains(todayDateLine) && todayDateLine.equals(data)) {
                                            Paint mPaint = new Paint();
                                            mPaint.setColor(getResources().getColor(R.color.yellow));
                                            mPaint.setStyle(Paint.Style.STROKE);
                                            mPaint.setStrokeWidth(2);//这个地方改线宽,单位是像素
                                            mPaint.setAntiAlias(true);//抗锯齿
//                                            canvas.drawCircle(rect.centerX(), rect.centerY(), rect.width() / 2.5F, paint);
                                            RectF oval = new RectF(rect.centerX() - rect.width() / 2.5F, rect.centerY() - rect.width() / 2.5F,
                                                    rect.centerX() + rect.width() / 2.5F, rect.centerY() + rect.width() / 2.5F);
                                            canvas.drawArc(oval, 0, 360, false, mPaint);
                                        }
                                    }

                                });
                                binding.mainDp.invalidate();
                            }
                        } else if (response.get("code").toString().equals("501")) {
                            JSONObject object = JSON.parseObject(response.get("data").toString());
                            locationRadius = object.getDouble("locationRadius");
                        }
                    }
                });
    }

    /**
     * 查询某一天签到详情
     *
     * @param date
     */
    private void queryDayDetail(String date) {

        String[] dateArr = date.split("-");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("year", dateArr[0]);
        jsonObject.put("month", dateArr[1]);
        jsonObject.put("day", dateArr[2]);
        OkHttpUtils
                .postString()
                .url(ApiConfig.DETAIL_SIGN)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(SignInActivity.this, response)) {
                            JSONArray jsonArray = JSON.parseArray(response.get("data").toString());
                            dialogSignState.setData(jsonArray);
                        }
                    }
                });
    }

    /**
     * 获取个人信息(查询当前用户有几个可签到的共享店)
     */
    private void getInfoData() {
        progressDialog.show();
        OkHttpUtils
                .get()
                .url(ApiConfig.PERSONAL_INFO)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(SignInActivity.this, response, null)) {
                            JSONObject object = JSON.parseObject(response.get("data").toString());
                            storeList = JSON.parseObject(object.getJSONArray("coordinateList").toString(), new TypeReference<ArrayList<Map<String, String>>>() {
                            });
                            //region 保存用户信息
                            String imageUrl = String.valueOf(object.get("imageUrl"));
                            String userName = object.getString("name");
                            String telNum = object.getString("tel");
                            String titleLevel = object.getString("titleLevel");
                            String email = object.getString("email");
                            String deptName = object.getString("deptName");
                            String shareStoreName = object.getString("shareStoreName");

                            SharePTool.UserInfoBean bean = new SharePTool.UserInfoBean();
                            bean.setImageUrl(imageUrl);
                            bean.setEmail(email);
                            bean.setTelNum(telNum);
                            bean.setTitleLevel(titleLevel);
                            bean.setDeptName(deptName);
                            bean.setUserName(userName);
                            bean.setShareStoreName(shareStoreName);

                            SharePTool.saveUserInfoBean(SignInActivity.this, bean);
                            //endregion
                            QuerySign();
                        }
                    }
                });
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == 62) {
                CustomToast.showToast(SignInActivity.this, "定位失败，请检查GPS定位是否开启", 1500);
            } else if (location.getLocType() == 63) {
                CustomToast.showToast(SignInActivity.this, "网络异常，请检查网络是否正常", 1500);
            } else if (location.getLocType() == 161 || location.getLocType() == 61) {
                //网络定位或者GPS定位成功
                //当前定位位置
                currentLocation = location.getLocationDescribe();
                lat = location.getLatitude();
                lng = location.getLongitude();
                LatLng now = new LatLng(location.getLatitude(), location.getLongitude());
                if (storeList.size() > 0) {
                    for (int i = 0; i < storeList.size(); i++) {
                        LatLng store = new LatLng(Double.parseDouble(StringUtil.valueOf(storeList.get(i).get("pointx"), "0")),
                                Double.parseDouble(StringUtil.valueOf(storeList.get(i).get("pointy"), "0")));
                        distance = DistanceUtil.getDistance(now, store);
                        if (distance < locationRadius) {
                            LocationDialog.dismiss();
                            break;
                        }
                        if (i == storeList.size() - 1) {
                            LocationDialog.dismiss();
                        }
                    }
                } else {
                    LocationDialog.dismiss();
                }
            } else {
                LocationDialog.dismiss();
                CustomToast.showToast(SignInActivity.this, "发生未知错误，请检查网络与GPS定位是否开启", 1500);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        mLocClient.stop();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public String getNowTime() {
        String nowTime = DateUtil.getTime(System.currentTimeMillis(), "yyyy-M-d");
        return nowTime;
    }

    @Subscriber(tag = "TAG_SIGNIN_DATA")
    public void data(ArrayList<Map<String, String>> list) {
        EventBus.getDefault().removeStickyEvent(list.getClass(), "TAG_SIGNIN_DATA");
        this.storeList = list;
    }

}
